//
//  BTHandler.m
//  CoolRollerSkating
//
//  Created by CA on 15/11/30.
//  Copyright © 2015年 Coollang. All rights reserved.
//

#import "BTHandler.h"
#import "SportRecordItem.h"
#import "BarChartItem.h"
#import <DateTools/DateTools.h>


@implementation BTHandler

#pragma mark - Private Method

+ (void)verifyData:(NSData *)data withFunctionCode:(NSInteger)functionCode withCompetitionBlock:(CompletionBlock)completionBlock
{
    if (![data isKindOfClass:[NSData class]]) {
        return;
    }
    
    const u_int8_t *bytes = [data bytes];
    if (data.length == 20) {
        if (bytes[1] == functionCode) {
            completionBlock(YES);
        }else{
            completionBlock(NO);
            
        }
    }else{
        completionBlock(NO);
        
    }
}

+ (BOOL)checkDataType:(NSData *)data
{
    if (![data isKindOfClass:[NSData class]]) {
        return NO;
    }
    
    return YES;
}

+ (BOOL)checkDataArrayType:(NSArray *)dataArray
{
    if (![dataArray isKindOfClass:[NSArray class]]) {
        return NO;
    }
    
    return YES;
}


#pragma mark - Public Method

+ (void)handleGetInfomationFeedbackData:(NSData *)data withInformationBlock:(GetInformationBlock)block
{
    if (![self checkDataType:data]) {
        return;
    }
    
    const u_int8_t *bytes = [data bytes];
    if (data.length == 20) {
        
        NSInteger stepCount = bytes[2] * 256 + bytes[3];
        NSInteger fallOverCount = bytes[4] * 256 + bytes[5];
        NSInteger unixTimeStamp = bytes[6] * 256 * 256 * 256 + bytes[7] * 256 * 256 + bytes[8] * 256 + bytes[9];
        
        if (block) {
            block(stepCount, fallOverCount, unixTimeStamp);
        }
        
    }
}

+ (void)handleDeviceNameChangeData:(NSData *)data withCompetitionBlock:(CompletionBlock)completionBlock
{
    [self verifyData:data withFunctionCode:0x12 withCompetitionBlock:completionBlock];
}

+ (void)handleBatteryData:(NSData *)data withCompletion:(GetBatteryBlock)block
{
    if (![self checkDataType:data]) {
        return;
    }
    
    const u_int8_t *bytes = [data bytes];
    if (data.length == 20) {
        block(bytes[2]);
    }
}

+ (void)handleRestartDeviceData:(NSData *)data withCompletion:(CompletionBlock)block
{
    [self verifyData:data withFunctionCode:0x02 withCompetitionBlock:block];
}

+ (void)handleCloseDeviceData:(NSData *)data withCompletion:(CompletionBlock)block
{
    [self verifyData:data withFunctionCode:0x01 withCompetitionBlock:block];
}

+ (void)handleUpdateDeviceData:(NSData *)data withCompletion:(CompletionBlock)block
{
    [self verifyData:data withFunctionCode:0x05 withCompetitionBlock:block];
}

+ (void)handleCleanData:(NSData *)data withCompletion:(CompletionBlock)block
{
    [self verifyData:data withFunctionCode:0x03 withCompetitionBlock:block];
}

+ (void)handleResetData:(NSData *)data withCompletion:(CompletionBlock)block
{
    [self verifyData:data withFunctionCode:0x04 withCompetitionBlock:block];
}

+ (void)handleDeviceVersionData:(NSData *)data withCompletion:(VersionBlock)block
{
    if (![self checkDataType:data]) {
        return;
    }
    
    Byte bytes[6];
    const u_int8_t *dataBytes = [data bytes];
    if (data.length == 20) {
        if (dataBytes[1] == 0x21) {
            for (NSInteger i = 0; i < 6; i++) {
                bytes[i] = dataBytes[i+2];
            }
            NSData *versionData = [NSData dataWithBytes:bytes length:sizeof(bytes)];
            NSString * version = [[NSString alloc] initWithData:versionData encoding:NSUTF8StringEncoding];
            block(YES,version);
        }else{
            block(NO,nil);
        }
    }else{
        block(NO,nil);
    }
}

+ (void)handleHandData:(NSData *)data withCompletion:(FeedbackDataBlock)block
{
    if (![self checkDataType:data]) {
        return;
    }
    
    const u_int8_t *bytes = [data bytes];
    if (data.length == 20) {
        NSInteger hand = bytes[2];
        if (bytes[1] == 0x13) {
            block(YES,[@(hand) stringValue]);
        }else{
            block(NO,nil);
        }
    }else{
        block(NO,nil);
    }
    
}

+ (void)handleRuntimeData:(NSData *)data withCompletion:(RunTimeDataBlock)block
{
    if (![self checkDataType:data]) {
        return;
    }
    
    const u_int8_t *bytes = [data bytes];
    if (data.length != 20 || bytes[1] != 0x24) {
        block(NO,0, 0, 0, 0, 0, 0, 0);
        return;
    }
    
    SportPoseType actionType = 1;
    NSInteger speed = 0;
    NSInteger strength = 0;
    NSInteger radian = 0;
    NSInteger hitball = 0;
    NSInteger topBottomBall = 0;
    NSInteger forebackBall = 0;
    
    if (bytes[2] == 0x01) {
        actionType = [self parseActionType:bytes[3]];
        speed = bytes[4] * 256 + bytes[5];
        strength = bytes[6] *256 + bytes[7];
        radian= bytes[8] *256 + bytes[9];
        hitball= bytes[10] == 0x00 ? 0 : 1;
        topBottomBall = bytes[11] == 0x00 ? 0 : 1;
        forebackBall = bytes[12] == 0x00 ? 0 : 1;
        block(YES,actionType,speed,strength,radian,hitball,topBottomBall,forebackBall);
    }
    
}

+ (void)handleHomePageData:(NSMutableArray *)homePageArr withCompletion:(HomePageDataBlock)block
{
    if (![self checkDataArrayType:homePageArr]) {
        return;
    }
    
    NSMutableArray *sportItems = @[].mutableCopy;
    
    SportRecordItem *item = nil;
    for (NSData *data in homePageArr) {
        const u_int8_t *bytes = [data bytes];
        if (data.length != 20 || bytes[1] != 0x23) {
            continue;
        }
        if (bytes[2] == 0x01) {
            //step1
            item = [[SportRecordItem alloc] init];
            item.dateTimeStamp = (bytes[3] * 256 + bytes[4]) * 86400;
            NSDate *date = [NSDate dateWithUnixTimeStamp:item.dateTimeStamp];
            item.dateStr = [date formattedDateWithFormat:@"yyyy-MM-dd" timeZone:[NSTimeZone localTimeZone]];
            item.exerciseTimeInterval = bytes[5] * 256 + bytes[6];
            item.maxSpeed = bytes[9] * 256 +bytes[10];
        } else if (bytes[2] == 0x02) {
            //step2
            if (!item) {
                item = [[SportRecordItem alloc] init];
            }
            item.faQiuCount = bytes[3] * 256 + bytes[4];
            item.kouShaCount = bytes[5] * 256 + bytes[6];
            item.jieJiCount = bytes[7] * 256 + bytes[8];
            item.xueQiuCount = bytes[9] * 256 + bytes[10];
            item.xuanQiuCount = bytes[11] * 256 + bytes[12];
            item.pingJiCount = bytes[13] * 256 + bytes[14];
            item.calories = [item calculatedCalories];
            
            NSTimeInterval minTimeInterval = [[NSDate dateWithString:@"2014-09-15 00:00:00" formatString:@"yyyy-MM-dd HH:mm:ss"] unixTimeStamp];
            if (item.dateTimeStamp > minTimeInterval) {
                [sportItems addObject:item];
            }
        }else if (bytes[2] == 0x03) {
            
            [sportItems sortUsingComparator:^NSComparisonResult(SportRecordItem *obj1, SportRecordItem *obj2) {
                return obj1.dateTimeStamp < obj1.dateTimeStamp;
            }];
            
            block(YES,sportItems);
        }

    }
}

+ (void)handleSportDetailData:(NSData *)data barChartItemBlock:(BarChartItemBlock)barChartItemBlock completionBlock:(CompletionBlock)completionBlock
{
    const u_int8_t *bytes = [data bytes];
    if (data.length != 20 || bytes[1] != 0x25) {
        return;
    }
    
    BarChartItem *item = [[BarChartItem alloc] init];
    
    if (bytes[2] == 0x01) {
        item.poseType = [self parseActionType:bytes[3]];
        item.maxSpeed = [@(bytes[4] * 256 + bytes[5]) stringValue];
        item.strength    = [@(bytes[6] * 256 + bytes[7]) stringValue];
        item.arc  =  [@(bytes[8] + bytes[9]) stringValue];
        item.isHitSweet = bytes[10] == 0x01;
        item.unixTimeStamp = [@(bytes[11] * 256 * 256 * 256 + bytes[12] * 256 * 256 + bytes[13] * 256 + bytes[14]) stringValue];
        item.handType = (bytes[16] == 0x00 ? HandDirectionTypeForeward : HandDirectionTypeBackward);
        barChartItemBlock(item);
    } else if (bytes[2] == 0x02) {
        completionBlock(YES);
    }
}

+ (SportPoseType)parseActionType:(NSInteger)actionType {
    switch (actionType) {
        case 0x01:
            return SportPoseTypeKouSha;
            break;
        case 0x02:
            return SportPoseTypeJieJi;
            break;
        case 0x03:
            return SportPoseTypeXueQiu;
            break;
        case 0x04:
            return SportPoseTypeXuanQiu;
            break;
        case 0x05:
            return SportPoseTypePingJi;
            break;
                default:
            break;
    }
    return SportPoseTypeFaQiu;
}

+ (void)handleTimeStampVerifyData:(NSData *)data withCompletion:(CompletionBlock)block
{
    [self verifyData:data withFunctionCode:0x11 withCompetitionBlock:block];
}


@end
